<?
include "../db_config.php";
include "Database.class.php";
include_once "snoopy/Snoopy.class.php";
include_once "util.php";

function toTimeStamp($date)
{
	$d = split(":", $date);
	$month = date("n");
	$day = date("j");
	$year = date("Y");
	return mktime($d[0], $d[1], $d[2], $month, $day, $year);
}

$s_time = microtime(true);

$line = $HTTP_GET_VARS['line'];
$updown = $HTTP_GET_VARS['updown'];

$lat1 = $HTTP_GET_VARS['lat1'];
$lat2 = $HTTP_GET_VARS['lat2'];
$lng1 = $HTTP_GET_VARS['lng1'];
$lng2 = $HTTP_GET_VARS['lng2'];
$g_line = urldecode($HTTP_GET_VARS['line']);
$g_lines = split("\|", $g_line);

//$updown = 2;

$day = date("D");
if($day == "Sat")
	$week = 2;
else if($day == "Sun")
	$week = 3;
else
	$week = 1;

$totalNo = 0;

$db = new Database($host_name, $user_name, $db_password, $db_name);
$db->connect();

function printInfo($line, $updown)
{
	//echo $line . "호선" . $updown . "아래 ";
	global $db, $week, $totalNo;
	global $lat1, $lat2, $lng1, $lng2;
	$i = 0;

	$st = "startTime".$week;
	$ed = "endTime".$week;

	//$time = date('H:i:s');
	$time = getTime();
	//$time = '14:41:00'; 

	$currentTime = time();
	$sql = "select * from trainInfo";
	$where = " where $st <= '$time' and $ed >= '$time'";
	//$where = " where running=1";
	if($line != null)
		$where .= " and line = '$line'";
	if($updown != null)
		$where .= " and updown ='$updown' ";
	if($lat1 != null)
		$where .= " and lat >= $lat1";
	if($lat2 != null)
		$where .= " and lat <= $lat2";
	if($lng1 != null)
		$where .= " and lng >= $lng1";
	if($lng2 != null)
		$where .= " and lng <= $lng2";

	$sql .= $where;
//	echo $sql;

//	$t = $db->query_first("select count(*) from trainInfo".$where);
//	$totalNo += intval($t['count(*)']);

	//해당 열차 정보를 꺼내온다
	$rows = $db->fetch_all_array($sql);

	foreach($rows as $data)
	{
		$totalNo++;
		$lat = $data[lat];
		$lng = $data[lng];
		$trainId = $data[trainId];
		$remain = $data[remain];
		$line2 = $data[line];
		$updown2 = $data[updown];
		echo "{\"lat\":$lat,\"lng\":$lng,".
		"\"trainId\":\"$trainId\",\"remainTime\":$remain,".
		"\"line\":\"$line2\"},\n";//,\"updown\":\"$updown2\"},\n";
		//echo $s1[stationName] . " " . $s2[stationName] . "<BR>\n";
		$i++;
	}
}

echo "{\"Points\":[";

foreach($g_lines as $l)
{
	$l2 = split("_", $l);
	if($l2[1] != null)
		printInfo($l2[0], $l2[1]);
}

echo "],\"totalNum\":$totalNo}";
/*
$e_time = microtime(true);
$during = $e_time - $s_time;
$d = array();
$d[loading] = $during*1000.0;
$d[param] = $_SERVER[QUERY_STRING];
$d[totalNo] = $totalNo;
$d[ip] = $_SERVER['REMOTE_ADDR'];
$db->query_insert("subway_log", $d);
$no = $db->query_first("select COUNT(*) from subway_log");
//로그는 1000개만 관리하자
if($no['COUNT(*)'] > 1000)
{
	$sql = "delete from subway_log order by id limit 1";
	$db->query($sql);
}
*/
$db->close();
?>
